import { invoke } from "@tauri-apps/api/tauri";
import { EsIndexInfo } from "@/views/home/types.ts";
import NProgress from "@/utils/progress";
import { notification } from "ant-design-vue";
import { emitter } from "@/utils/mitt.ts";

export function useHome() {
	const homeBody = ref<HTMLElement>();
	const value = ref<string>("");
	const loading = ref<boolean>(false);
	const cardWidth = ref<string>("0px");
	const sortValue = ref<string>("默认排序");
	const sortOptions = ref([
		{
			label: "默认排序",
			value: "默认排序",
		},
		{
			label: "名称正序",
			value: "名称正序",
		},
		{
			label: "名称倒序",
			value: "名称倒序",
		},
		{
			label: "大小正序",
			value: "大小正序",
		},
		{
			label: "大小倒序",
			value: "大小倒序",
		},
		{
			label: "数量正序",
			value: "数量正序",
		},
		{
			label: "数量倒序",
			value: "数量倒序",
		},
	]);
	const filterValue = ref<string>("全部");
	const filterOptions = ref([
		{
			label: "全部",
			value: "全部",
		},
		{
			label: "Open",
			value: "Open",
		},
		{
			label: "Close",
			value: "Close",
		},
	]);
	const esIndexInfos = ref<EsIndexInfo[]>([]);
	const current = ref<number>(1);
	const total = ref<number>(0);
	const pageSize = ref<number>(20);
	const selectAllStatus = ref<boolean>(false);
	const cancelAllStatus = ref<boolean>(true);
	const allowOperations = ref<boolean>(true);
	const onSearch = () => {
		getIndices(true);
	};

	const onSortChange = () => {
		getIndices();
	};
	const onStatusChange = () => {
		getIndices();
	};

	const onPaginationChange = (page: number, size: number) => {
		current.value = page;
		pageSize.value = size;
		getIndices();
	};

	const initCardWidth = () => {
		if (homeBody.value) {
			const offsetWidth = homeBody.value.offsetWidth;
			if (offsetWidth < 900) {
				cardWidth.value = homeBody.value.offsetWidth + "px";
			} else if (offsetWidth < 1200) {
				cardWidth.value = (homeBody.value.offsetWidth - 23) / 2 + "px";
			} else {
				cardWidth.value = (homeBody.value.offsetWidth - 31) / 3 + "px";
			}
		}
	};

	function getIndices(refresh: boolean = false) {
		esIndexInfos.value = [];
		let search = undefined;
		if (value.value && value.value.length > 0) {
			search = value.value;
		}
		loading.value = true;
		NProgress.start();
		invoke("get_indices", {
			index: search,
			sort: sortValue.value,
			status: filterValue.value,
			page: current.value,
			size: pageSize.value,
			refresh: refresh,
		})
			.then((data: any) => {
				current.value = data.current;
				total.value = data.total;
				pageSize.value = data.size;
				esIndexInfos.value = data.data as EsIndexInfo[];
				changeSelectStatus();
			})
			.finally(() => {
				loading.value = false;
				NProgress.done();
			});
	}

	function handleRefresh() {
		invoke("refresh").then(() => {
			getIndices();
		});
	}

	function handleSelectAll() {
		esIndexInfos.value.forEach((item) => {
			item.select = true;
		});
		selectAllStatus.value = true;
		cancelAllStatus.value = false;
		allowOperations.value = false;
	}

	function checkboxChange(value: string) {
		esIndexInfos.value.forEach((item) => {
			if (item.index == value) {
				item.select = !item.select;
			}
		});
		changeSelectStatus();
	}

	function handleCancelAll() {
		esIndexInfos.value.forEach((item) => {
			item.select = false;
		});
		selectAllStatus.value = false;
		cancelAllStatus.value = true;
		allowOperations.value = true;
	}

	function handleDeleteSelectedIndex() {
		const indies = getSelectedIndies();
		if (indies.length > 0) {
			handleDeleteIndex(indies).finally(() => {
				handleRefresh();
				selectAllStatus.value = false;
				cancelAllStatus.value = true;
			});
		}
	}
	function handleCloseSelectedIndex() {
		const indies = getSelectedIndies();
		if (indies.length > 0) {
			handleCloseIndex(indies).finally(() => {
				handleRefresh();
				selectAllStatus.value = false;
				cancelAllStatus.value = true;
			});
		}
	}

	function handleOpenSelectedIndex() {
		const indies = getSelectedIndies();
		if (indies.length > 0) {
			handleOpenIndex(indies).finally(() => {
				handleRefresh();
				selectAllStatus.value = false;
				cancelAllStatus.value = true;
			});
		}
	}

	function getSelectedIndies() {
		const result: string[] = [];
		if (esIndexInfos.value) {
			esIndexInfos.value.forEach((item) => {
				if (item.select == true) {
					result.push(item.index);
				}
			});
		}
		return result;
	}

	const handleOpenIndex = (value: string[]) => {
		return new Promise((resolve) => {
			invoke("action_open_indices", { indices: value })
				.then((data: any) => {
					notification.info({
						message: "打开索引结果",
						description: JSON.stringify(data, null, "\t"),
						placement: "bottomRight",
					});
				})
				.finally(() => {
					resolve(true);
				});
		});
	};
	const handleDeleteIndex = (value: string[]) => {
		return new Promise((resolve) => {
			invoke("action_remove_indices", { indices: value })
				.then((data: any) => {
					notification.info({
						message: "删除索引结果",
						description: JSON.stringify(data, null, "\t"),
						placement: "bottomRight",
					});
				})
				.finally(() => {
					resolve(true);
				});
		});
	};

	const handleCloseIndex = (value: string[]) => {
		return new Promise((resolve) => {
			invoke("action_close_indices", { indices: value })
				.then((data: any) => {
					notification.info({
						message: "关闭索引结果",
						description: JSON.stringify(data, null, "\t"),
						placement: "bottomRight",
					});
				})
				.finally(() => {
					resolve(true);
				});
		});
	};

	function changeSelectStatus() {
		let number = 0;
		esIndexInfos.value.forEach((item) => {
			if (item.select == true) {
				number = number + 1;
			}
		});
		if (esIndexInfos.value && esIndexInfos.value.length > 0) {
			if (esIndexInfos.value.length == number) {
				// 全部被选中
				allowOperations.value = false;
				selectAllStatus.value = true;
				cancelAllStatus.value = false;
			} else if (number > 0) {
				// 部分选中
				allowOperations.value = false;
				selectAllStatus.value = false;
				cancelAllStatus.value = false;
			} else if (0 == number) {
				// 全部没有被选中
				allowOperations.value = true;
				selectAllStatus.value = false;
				cancelAllStatus.value = true;
			}
		} else {
			allowOperations.value = true;
			selectAllStatus.value = true;
			cancelAllStatus.value = true;
		}
	}

	onMounted(function () {
		getIndices(true);
		nextTick().then(() => {
			initCardWidth();
			window.onresize = () => {
				return (() => {
					initCardWidth();
				})();
			};
		});
		emitter.on("nodeChange", () => {
			getIndices(true);
		});
	});
	onUnmounted(function () {
		window.onresize = null;
		emitter.off("nodeChange");
	});

	return {
		homeBody,
		loading,
		value,
		cardWidth,
		sortValue,
		sortOptions,
		filterValue,
		filterOptions,
		esIndexInfos,
		current,
		total,
		pageSize,
		selectAllStatus,
		cancelAllStatus,
		allowOperations,
		onSearch,
		onSortChange,
		onStatusChange,
		onPaginationChange,
		handleRefresh,
		handleSelectAll,
		checkboxChange,
		handleCancelAll,
		handleDeleteSelectedIndex,
		handleCloseSelectedIndex,
		handleOpenSelectedIndex,
	};
}
